package com.aaa.dao.impl;

import com.aaa.dao.IBookDao;
import com.aaa.entity.Book;
import com.aaa.utils.DBUtil;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class IBookDaoImpl implements IBookDao {
    @Override
    public List<Book> findAllBook() {
        String sql = "select \n" +
                "a.*,b.typename\n" +
                "from t_book a ,t_type b where a.typeid=b.typeid";
        List<Map> maps = DBUtil.queryListMap(sql);
        ArrayList<Book> books = new ArrayList<>();
        if(maps.size()>0){
            for (Map map : maps) {
                Book book = new Book();
                //之前每一次做数据的封装都要去挨个设置，太麻烦
                try {
                    //把map中的数据封装到book对象中，确保实体类的字段名和map中的key值一样
                    BeanUtils.populate(book,map);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                books.add(book);
            }
            return books;
        }
        return null;
    }

    @Override
    public Integer updateStatus(Integer bookid, Integer status) {
        String sql = "update t_book set status=? where bookid=?";
        if(status==0){
            return  DBUtil.update(sql, 1, bookid);
        }else{
            return DBUtil.update(sql, 0, bookid);
        }
    }

    @Override
    public Integer delBookById(Integer bookid) {
        String sql = "delete from t_book where bookid=?";
        return DBUtil.update(sql, bookid);
    }

    @Override
    public Integer addBook(Book book) {
        String sql = "insert into t_book values(null,?,?,0,?,?,?,?,?)";
        return DBUtil.update(sql,
                book.getBookname(),
                book.getAuthor(),
                book.getRemark(),
                book.getTypeid(),
                book.getPublisher(),
                book.getPrice(),
                book.getStatus());
    }

    @Override
    public Integer updateBook(Book book) {
        String sql = "update t_book set bookname=? ,author=?,remark=?,typeid=?,publisher=?,price=?,status=? where bookid=?";
        return  DBUtil.update(sql,book.getBookname(),
                book.getAuthor(),
                book.getRemark(),
                book.getTypeid(),
                book.getPublisher(),
                book.getPrice(),
                book.getStatus(),
                book.getBookid());
    }
}
